package drds.common.db.xml_mapping.executor;


import drds.common.db.xml_mapping.executor.statement.StatementHandler;
import drds.common.db.xml_mapping.mapping.BindSql;
import drds.common.db.xml_mapping.mapping.Mapper;
import drds.common.db.xml_mapping.session.Configuration;
import drds.common.db.xml_mapping.session.ResultHandler;
import drds.common.db.xml_mapping.session.RowBounds;
import drds.common.db.xml_mapping.transaction.Transaction;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collections;
import java.util.List;


public class SimpleExecutor extends BaseExecutor {

  public SimpleExecutor(Configuration configuration, Transaction transaction) {
    super(configuration, transaction);
  }

  @Override
  public int doUpdate(Mapper mapper, Object parameter) throws SQLException {
    Statement statement = null;
    try {
      Configuration configuration = mapper.getConfiguration();
      StatementHandler statementHandler = configuration.newStatementHandler(this, mapper, parameter, RowBounds.DEFAULT, null, null);
      statement = prepareStatement(statementHandler);
      return statementHandler.update(statement);
    } finally {
      closeStatement(statement);
    }
  }

  @Override
  public <E> List<E> doQuery(Mapper mapper, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BindSql bindSql) throws SQLException {
    Statement statement = null;
    try {
      Configuration configuration = mapper.getConfiguration();
      StatementHandler statementHandler = configuration.newStatementHandler(executor, mapper, parameter, rowBounds, resultHandler, bindSql);
      statement = prepareStatement(statementHandler);
      return statementHandler.query(statement, resultHandler);
    } finally {
      closeStatement(statement);
    }
  }


  @Override
  public List<BatchResult> doFlushStatements(boolean isRollback) {
    return Collections.emptyList();
  }

  private Statement prepareStatement(StatementHandler statementHandler) throws SQLException {
    Statement statement;
    Connection connection = getConnection();
    statement = statementHandler.prepare(connection, transaction.getTimeout());
    statementHandler.parameterize(statement);
    return statement;
  }

}
